public class HashBuck {
    static class Node{
        public int key;
        public int val;
        public Node next;
        public Node(int key, int val){
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array;
    public int usedSize;
    public HashBuck(){
        this.array = new Node[10];
    }
    public void put(int key, int val){
        int index = key % this.array.length;
        Node node = new Node(key, val);
        //先遍历链表，看一看是不是有这个节点，有就更新值
        Node cur = array[index];
        while(cur !=  null){
            if(cur.key == key){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //cur == null 证明链表里面没有这个节点
        //使用头插法进行插入
        node.next = array[index];
        array[index] = node;
        usedSize++;

        Node curNext = array[index].next;
        //放元素之前先计算下容量是不是达到75%
        if(loadFactor() >= 0.75){
            //扩大散列表长度 resize
            resize();
        }
    }
    private void resize(){
        Node[] tmpArr = new Node[2 * array.length];
        //扩容之后每个节点都要 重新哈希，所以要遍历每一个节点
        for(int i = 0; i < array.length; i++){
            Node cur = array[i];
            while(cur != null){
                int newIndex = cur.key % tmpArr.length;
                //在新链表进行头插
                Node curNext = cur.next;
                cur.next = tmpArr[newIndex];
                tmpArr[newIndex] = cur;
                cur = curNext;
            }
        }
        array = tmpArr;
    }
    private double loadFactor(){
        return (this.usedSize * 1.0) / this.array.length;
    }

    public int get(int key){
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }
}
